//
//  NewsViewController.m
//  Unicorn
//
//  Created by zhupeng on 16/5/3.
//  Copyright © 2016年 bhj_jun. All rights reserved.
//

#import "NewsViewController.h"
#import "NewsDetailViewController.h"
#import "iCarousel.h"
#import "HeadView.h"
#import "NewsFirstCell.h"
@interface NewsViewController ()<UITableViewDelegate,UITableViewDataSource,iCarouselDelegate>

@property (nonatomic,retain)UITableView *tableView;
@property (nonatomic,retain)NSMutableArray *allDataArray;

@property (nonatomic,retain)HeadView *headView;
//@property (nonatomic,retain)NSMutableArray *ImageArr;
@property (nonatomic,assign)NSInteger addNumber;
@property (nonatomic ,retain)NSDate *refreshTime;
@property (nonatomic,retain)NSMutableArray *headViewArr;

@end

@implementation NewsViewController
#pragma mark - 属性懒加载

-(NSMutableArray *)allDataArray{
    
    if (!_allDataArray) {
        _allDataArray = [[NSMutableArray alloc]init];
        
    }
    return _allDataArray;
}

-(NSMutableArray *)headViewArr{
    
    if (!_headViewArr) {
        _headViewArr = [[NSMutableArray alloc]init];
    }
    
    return _headViewArr ;
}
-(UITableView *)tableView{
    
    if (!_tableView) {
        _tableView =[[UITableView alloc]initWithFrame:self.view.frame];
        _tableView.delegate =self;
        _tableView.dataSource =self;
    }
    return _tableView;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.addNumber =2;
    [self.view addSubview:self.tableView];
    [self fetchDataWithUrl:KshehuiUrl withRequestType:self.requestType];
    [self refreshData];
    //    cell的高度自适应
    self.tableView.estimatedRowHeight  = 68;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    [self.tableView registerNib:[UINib nibWithNibName:@"NewsFirstCell" bundle:nil] forCellReuseIdentifier:@"NewsFirstCell"];
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark - 数据请求

-(void)fetchDataWithUrl:(NSString *)url withRequestType:(requestType)requestType{
    AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        switch (self.requestType) {
            case loadType:
            {
                NSLog(@"数据请求成功");
                //        数据解析
                NSDictionary *sourceDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
                NSDictionary *dataDic = [sourceDic objectForKey:@"data"];
                NSArray *itemListArr =[dataDic objectForKey:@"itemList"];
                
                //        显示列表的数据
                for (NSDictionary *dic in itemListArr) {
                    YaowenModel *model =[[YaowenModel alloc] init];
                    [model setValuesForKeysWithDictionary:dic];
                    
                    //                    判断是否是专题信息
                    if (![model.pubDate isEqualToString:@"0"]) { //如果不是则存储
                        
                        [self.allDataArray addObject:model];
                    }
                }
                [self creatTableHeadView];
                [self.tableView.mj_header endRefreshing];
                
            }
                break;
                
            case addType:
            {
                //        数据解析
                NSDictionary *sourceDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
                NSArray *itemListArr =[sourceDic objectForKey:@"itemList"];
                //        显示列表的数据
                for (NSDictionary *dic in itemListArr) {
                    YaowenModel *model =[[YaowenModel alloc] init];
                    [model setValuesForKeysWithDictionary:dic];
                    [self.allDataArray addObject:model];
                }
                [self.tableView.mj_footer endRefreshing];
            }
                break;
                
            default:
                break;
        }
        
        [MBProgressHUD hideAllHUDsForView:self.view  animated:YES];
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"0");
    }];
    
}

#pragma mark - ---tableViewDataSource--
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.allDataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    
    NewsFirstCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsFirstCell" forIndexPath:indexPath];
    
    YaowenModel *model = self.allDataArray[indexPath.row];
    [cell setCellWithModel:model];
    
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    return cell;
    
    
}



#pragma mark - ----tableViewDelegate----

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NewsDetailViewController *newsDetailVC =[[NewsDetailViewController alloc]init];
    
    YaowenModel *model =[self.allDataArray objectAtIndex:indexPath.row];
    
    newsDetailVC.YModel =model;
    
    
    
    [self.navigationController pushViewController:newsDetailVC animated:YES];
    
    
    
}

#pragma  mark - ----上拉加载  下拉刷新----

-(void)refreshData{
    //    上拉加载
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.requestType =addType;
        
        [self fetchDataWithUrl:[NSString stringWithFormat:KshehuiAddUrl,self.addNumber] withRequestType:self.requestType];
        
        self.addNumber++;
        
    }];
    //    下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //        距离上次刷新的时间
        NSTimeInterval time = [[NSDate date] timeIntervalSinceDate:self.refreshTime];
        //        NSLog(@"时间间隔--%f",time);//测试
        if (time<10) {
            
            UIAlertView *alert = [[UIAlertView  alloc]initWithTitle:@"已经是最新消息啦" message:@"别浪费流量啊亲 流量很贵的哦" delegate:self cancelButtonTitle:@"继续浏览" otherButtonTitles: nil];
            [alert show];
            
            [self.tableView.mj_header endRefreshing];
        }else{
            
            self.requestType =loadType;
            self.allDataArray =[NSMutableArray array];
            
            self.addNumber =2;
            [self fetchDataWithUrl:KshehuiUrl withRequestType:self.requestType];
            self.refreshTime =[NSDate date];
            
        }
        
    }];
    
    
}
#pragma mark - 页面设计
//创建表头视图
-(void)creatTableHeadView{
    NSMutableArray *  ImageArr =[[NSMutableArray alloc]init];
    
    for (int i=3; i<_allDataArray.count; i+=2) {
        YaowenModel *model = self.allDataArray[i];
        [self.headViewArr addObject:model];
        
    }
    
    
    for (int i=0; i<_headViewArr.count; i++) {
        YaowenModel *model =[_headViewArr objectAtIndex:i];
        UIImage *iamge =[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:model.itemImageDic[@"imgUrl1"]]]];
        [ImageArr addObject:iamge];
    }
    
    _headView = [[HeadView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 200) ImageArray:ImageArr];
    _headView.carousel.type =iCarouselTypeCoverFlow2;
    _headView.carousel.delegate =self;
    
    self.tableView.tableHeaderView=self.headView;
    
}

#pragma mark - 头视图中旋转木马的代理方法

//属性设置代理方法

-(CGFloat)carousel:(iCarousel *)carousel valueForOption:(iCarouselOption)option withDefault:(CGFloat)value{
    
    switch (option)
    {
        case iCarouselOptionWrap://这个case里面返回是否循环
        {
            return YES;
        }
        case iCarouselOptionSpacing://返回每个item间的距离
        {
            //add a bit of spacing between the item views
            return value * 1;
        }
        case iCarouselOptionFadeMax:
        {
            if (carousel.type == iCarouselTypeCustom)
            {
                //set opacity based on distance from camera
                return 0.0f;
            }
            return value;
        }
        default:
        {
            return value;
        }
    }
    
}

-(void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index{
    
    
    
    NewsDetailViewController *newsDetailVC =[[NewsDetailViewController alloc]init];
    
    YaowenModel *model =[self.headViewArr objectAtIndex:index];
    
    newsDetailVC.YModel =model;
    
    
    
    [self.navigationController pushViewController:newsDetailVC animated:YES];
    
    
    
}



/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

